package org.example.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOssTool {
    @Autowired
    private AliOSSProperties aliOSSProperties;
    // application.properties文件中定义的
//    @Value("${aliyun.oss.endpoint}")
//    private final String endpoint = aliOSSProperties.getEndpoint();
//    @Value("${aliyun.oss.bucketName}")
//    private final String bucketName = aliOSSProperties.getBucketName();

    /**
     * 实现文件上传到 oss
     */
    public String upload(MultipartFile file) throws IOException, ClientException {
        //    @Value("${aliyun.oss.endpoint}")
        String endpoint = aliOSSProperties.getEndpoint();
//    @Value("${aliyun.oss.bucketName}")
        String bucketName = aliOSSProperties.getBucketName();
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = "";
        if (originalFilename != null) {
            // 获取时间戳
            String time = String.valueOf(System.currentTimeMillis());
            fileName = time + originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        ossClient.putObject(bucketName, fileName, inputStream);
        String url =endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭 ossClient
        ossClient.shutdown();
        return url;
    }
}